import 'package:xws/helpers/as_t.dart';
import 'package:xws/models/notify/chat_msg_obj.dart';
import 'package:xws/models/notify/chat_obj.dart';
import 'package:xws/models/notify/sys_notify.dart';
import 'package:xws/models/res_obj.dart';
import 'package:xws/models/user/feedback_obj.dart';
import 'package:xws/models/user/user_basic_info.dart';
import 'package:xws/models/user/user_obj.dart';
import 'package:xws/models/user/user_update_obj.dart';
import 'package:xws/state/app_state.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/log_util.dart';

import '../request_apis.dart';
import '../request_source.dart';

/// 获取手机验证码
Future<bool> getSmsCode(String phone) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.smsCode,
      data: <String, dynamic>{'phone': phone},
      contentType: 'application/x-www-form-urlencoded',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    st('发送成功');
    return true;
  } catch (e) {
    error('获取手机验证码出错:$e');

    return false;
  }
}

/// 用户登录
Future<String?> userLogin(String phone, String code) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.login,
      method: 'get',
      data: <String, dynamic>{'phone': phone, 'code': code},
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return null;
    }

    st('登录成功');
    return res.data.toString();
  } catch (e) {
    error('用户登录出错:$e');

    return null;
  }
}

/// 用户退出登录
Future<void> userLogout() async {
  try {
    await getObj<ResObj>(
      APIS.logout,
      method: 'get',
      contentType: 'application/x-www-form-urlencoded',
    );
  } catch (e) {
    error('用户退出登录出错:$e');
  }
}

/// 获取用户基础数据
Future<UserBasicInfo?> userBasicInfo() async {
  try {
    if (!isLogin) return null;

    final ResObj? res = await getObj<ResObj>(
      APIS.myBasicInfo,
      method: 'get',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return null;
    }

    return UserBasicInfo.fromJson(asSDMap(res.data));
  } catch (e) {
    error('获取用户基础数据出错:$e');

    return null;
  }
}

/// 更新用户基础数据
Future<bool> updateInfo(UserUpdateObj updateObj) async {
  try {
    if (!isLogin) return false;

    final ResObj? res = await getObj<ResObj>(
      APIS.updateInfo,
      method: 'put',
      data: updateObj.toJson(),
      contentType: 'application/json',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    return res.success;
  } catch (e) {
    error('更新用户基础数据出错:$e');

    return false;
  }
}

/// 获取好友列表
Future<List<User>> getFriedns({
  int? pageNum,
  int pageSize = 10,
}) async {
  try {
    return await getList<User>(
      APIS.friends,
      dataKey: 'records',
      contentType: 'application/json',
      data: <String, dynamic>{
        if (pageNum != null) 'pageNum': pageNum,
        'pageSize': pageSize,
      },
    );
  } catch (e) {
    error('获取好友列表出错:$e');

    return <User>[];
  }
}

/// 获取黑名单列表
Future<List<User>> getBlackList({
  int? pageNum,
  int pageSize = 10,
}) async {
  try {
    return await getList<User>(
      APIS.blackList,
      dataKey: 'records',
      contentType: 'application/json',
      data: <String, dynamic>{
        if (pageNum != null) 'pageNum': pageNum,
        'pageSize': pageSize,
      },
    );
  } catch (e) {
    error('获取黑名单列表出错:$e');

    return <User>[];
  }
}

/// 搜索用户
Future<List<User>> searchUser({
  String? keyword,
  int? pageNum,
  int pageSize = 10,
}) async {
  try {
    return await getList<User>(
      APIS.searchUser,
      dataKey: 'records',
      contentType: 'application/json',
      data: <String, dynamic>{
        'keyword': keyword,
        if (pageNum != null) 'pageNum': pageNum,
        'pageSize': pageSize,
      },
    );
  } catch (e) {
    error('搜索用户出错:$e');

    return <User>[];
  }
}

/// 删除账户
Future<bool> delAccount() async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.delAccount,
      method: 'delete',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    return res.success;
  } catch (e) {
    error('删除账户出错:$e');
    return false;
  }
}

/// 添加好友
Future<bool> addFriend(String userId) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.addFriend,
      data: <String, dynamic>{'userId': userId},
      contentType: 'application/x-www-form-urlencoded',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    await apps.refreshFriendGoods();

    return res.success;
  } catch (e) {
    error('添加好友出错:$e');

    return false;
  }
}

/// 移除好友
Future<bool> delFriend(String userId) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.delFriend,
      method: 'delete',
      data: <String, dynamic>{'userId': userId},
      contentType: 'application/x-www-form-urlencoded',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    await apps.refreshFriendGoods();

    return res.success;
  } catch (e) {
    error('移除好友出错:$e');

    return false;
  }
}

/// 拉黑用户
Future<bool> blackUser(String userId) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.blackUser,
      data: <String, dynamic>{'userId': userId},
      contentType: 'application/x-www-form-urlencoded',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    await apps.refreshFriendGoods();
    await apps.refreshNearGoods();

    return res.success;
  } catch (e) {
    error('拉黑用户出错:$e');

    return false;
  }
}

/// 取消拉黑用户
Future<bool> unBlackUser(String userId) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.unBlackUser,
      method: 'delete',
      data: <String, dynamic>{'userId': userId},
      contentType: 'application/x-www-form-urlencoded',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    await apps.refreshFriendGoods();
    await apps.refreshNearGoods();

    return res.success;
  } catch (e) {
    error('取消拉黑用户出错:$e');

    return false;
  }
}

/// 向 `userId` 的用户发起聊天
Future<ChatObj?> createChat(String userId, String goodsId) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.createChat,
      data: <String, dynamic>{
        'userId': userId,
        'goodsId': goodsId,
      },
      contentType: 'application/x-www-form-urlencoded',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return null;
    }

    return ChatObj.fromJson(asSDMap(res.data));
  } catch (e) {
    error('发起聊天出错:$e');

    return null;
  }
}

/// 获取聊天列表
Future<List<ChatObj>> getChatList({
  int pageNum = 1,
  int pageSize = 20,
  RoomType? chatType,
}) async {
  try {
    return await getList<ChatObj>(
      APIS.chatList,
      dataKey: 'records',
      contentType: 'application/json',
      data: <String, dynamic>{
        'pageNum': pageNum,
        if (chatType != null) 'chatType': chatType.str,
        'pageSize': pageSize,
      },
    );
  } catch (e) {
    error('获取聊天列表出错:$e');

    return <ChatObj>[];
  }
}

/// 获取聊天内容
Future<List<ChatMegObj>> chatData({
  int? pageNum,
  int pageSize = 10,
  String? conversationId,
}) async {
  try {
    return await getList<ChatMegObj>(
      APIS.enterChat,
      dataKey: 'records',
      contentType: 'application/json',
      data: <String, dynamic>{
        if (pageNum != null) 'pageNum': pageNum,
        if (conversationId != null) 'conversationId': conversationId,
        'pageSize': pageSize,
      },
    );
  } catch (e) {
    error('获取聊天内容出错:$e');

    return <ChatMegObj>[];
  }
}

/// 获取系统消息
Future<List<SysNotify>> notifyData({
  int? pageNum,
  int pageSize = 10,
  String? conversationId,
}) async {
  try {
    return await getList<SysNotify>(
      APIS.enterChat,
      dataKey: 'records',
      contentType: 'application/json',
      data: <String, dynamic>{
        if (pageNum != null) 'pageNum': pageNum,
        if (conversationId != null) 'conversationId': conversationId,
        'pageSize': pageSize,
      },
    );
  } catch (e) {
    error('获取聊天内容出错:$e');

    return <SysNotify>[];
  }
}

/// 发送私信
Future<bool?> setMsg({
  String? content,
  String? conversationId,
  MsgType msgType = MsgType.TEXT,
}) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.sendMessage,
      data: <String, dynamic>{
        'content': content,
        'conversationId': conversationId,
        'messageType': msgType.str,
      },
      contentType: 'application/json',
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return null;
    }

    return res.success;
  } catch (e) {
    error('发送私信出错:$e');

    return null;
  }
}

/// 意见反馈
Future<bool> feedback(FeedbackObj feedbackObj) async {
  try {
    final ResObj? res = await getObj<ResObj>(
      APIS.feedback,
      data: feedbackObj.toJson(),
    );

    if (res == null || !res.success) {
      ct(res?.message ?? '网络错误');
      return false;
    }

    return res.success;
  } catch (e) {
    error('意见反馈出错:$e');

    return false;
  }
}
